package com.hpli.domain.award.service.distribute.impl;


import com.hpli.domain.award.model.aggregate.GiveOutPrizesAggregate;
import com.hpli.domain.award.model.entity.DistributeAwardEntity;
import com.hpli.domain.award.model.entity.UserAwardRecordEntity;
import com.hpli.domain.award.model.entity.UserCreditAwardEntity;
import com.hpli.domain.award.model.valobj.AwardStateVO;
import com.hpli.domain.award.repository.IAwardRepository;
import com.hpli.domain.award.service.distribute.IDistributeAward;
import com.hpli.types.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * @Author: 汀
 * @CreateTime: 2025-04-21
 * @Description: 用户积分奖品，支持award_config透传，满足黑名单积分奖励
 * @Version: 1.0
 */

@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward {

    @Resource
    private IAwardRepository repository;

    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAward) {
        // 奖品Id
        Integer awardId = distributeAward.getAwardId();
        // 查询奖品ID 【优先走透传的随机积分奖品配置】
        String awardConfig = distributeAward.getAwardConfig();
        if (StringUtils.isBlank(awardConfig)) {
            awardConfig = repository.queryAwardConfig(awardId);
        }

        String[] creditRange = awardConfig.split(Constants.SPLIT);
        if (creditRange.length != 2) {
            throw new RuntimeException("award_config [" + awardConfig + "] 配置不是一个范围值，如1,100");
        }

        // 生成随机积分值
        BigDecimal creditAmount = generateRandom(new BigDecimal(creditRange[0]), new BigDecimal(creditRange[1]));

        // 构建聚合对象
        UserAwardRecordEntity userAwardRecord = GiveOutPrizesAggregate.buildDistributeUserAwardRecordEntity(
                distributeAward.getUserId(),
                distributeAward.getOrderId(),
                distributeAward.getAwardId(),
                AwardStateVO.complete
        );

        UserCreditAwardEntity userCreditAward = GiveOutPrizesAggregate.buildUserCreditAwardEntity(
                distributeAward.getUserId(),
                creditAmount
        );

        GiveOutPrizesAggregate giveOutPrizesAggregate = new GiveOutPrizesAggregate();
        giveOutPrizesAggregate.setUserId(distributeAward.getUserId());
        giveOutPrizesAggregate.setUserAwardRecordEntity(userAwardRecord);
        giveOutPrizesAggregate.setUserCreditAwardEntity(userCreditAward);

        // 存储发奖对象
        repository.saveGiveOutPrizesAggregate(giveOutPrizesAggregate);

    }

    private BigDecimal generateRandom(BigDecimal min, BigDecimal max) {
        if (min.equals(max)) return min;
        BigDecimal randomBigDecimal = min.add(BigDecimal.valueOf(Math.random()).multiply(max.subtract(min)));
        return randomBigDecimal.round(new MathContext(3));
    }
}
